import json
from http.server import HTTPServer, SimpleHTTPRequestHandler
import webbrowser
import os
import logging
import sys
from typing import Optional

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

class Config:
    PORT = 8000
    HOST = 'localhost'
    ALLOWED_ORIGINS = ['http://localhost:8000']
    PRIVATE_JSON_PATH = os.path.join('resources', 'private.json')

def load_api_types():
    try:
        with open(Config.PRIVATE_JSON_PATH, 'r', encoding='utf-8') as f:
            data = json.load(f)
            return data.get('APITypes', {}).get('items', [])
    except Exception as e:
        logging.error(f"Error loading API types: {e}")
        return []

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        origin = self.headers.get('Origin')
        if origin in Config.ALLOWED_ORIGINS:
            self.send_header('Access-Control-Allow-Origin', origin)
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

    def log_message(self, format: str, *args) -> None:
        """Override to use our logging configuration"""
        logging.info(f"{self.address_string()} - {format%args}")

    def do_OPTIONS(self) -> None:
        """Handle preflight requests"""
        self.send_response(200)
        self.end_headers()

    def do_GET(self) -> None:
        """Handle GET requests"""
        if self.path == '/api/types':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            api_types = load_api_types()
            self.wfile.write(json.dumps(api_types).encode())
        else:
            super().do_GET()

def run(port: int = Config.PORT, host: str = Config.HOST) -> None:
    try:
        server_address = (host, port)
        httpd = HTTPServer(server_address, CORSRequestHandler)
        url = f'http://{host}:{port}'
        logging.info(f"Server running at {url}")
        
        try:
            webbrowser.open(url)
        except Exception as e:
            logging.warning(f"Failed to open browser: {e}")
        
        httpd.serve_forever()
    except KeyboardInterrupt:
        logging.info("Server stopped by user")
        httpd.server_close()
    except Exception as e:
        logging.error(f"Server error: {e}")
        sys.exit(1)

if __name__ == '__main__':
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    run()
